import { adminMenus } from '@/api/system/menu'
import router from "@/router/index";
import { routes, asyncRouterMap } from "@/router/index";
import { notFound } from '@/router/modules/error'
import common from "@/router/common";
import { RouteRecordRaw } from "vue-router";

// 根据路由名称获取菜单
const getMenu = (name, menus) => {
    for (let i = 0; i < menus.length; i++) {
        const menu = menus[i]
        if (name === menu.name) {
            return menu
        }
    }
    return null
}

// 判断是否有权限访问该菜单
const hasPermission = (menus, route) => {
    if (route.name) {
        const currMenu = getMenu(route.name, menus)
        if (currMenu !== null) {
            route.name = route.path
            //设置菜单的标题、图标和可见性
            if (currMenu.title != null && currMenu.title !== '') {
                route.meta.title = currMenu.title;
            }
            if (currMenu.icon != null && currMenu.title !== '') {
                route.meta.icon = currMenu.icon || '';
            }
            if (currMenu.hidden != null) {
                route.hidden = currMenu.hidden !== 0;
            }
            if (currMenu.sort != null && currMenu.sort !== '') {
                route.sort = currMenu.sort;
            }
            return true
        }   else {
            route.sort = 0
            if (route.hidden !== undefined && route.hidden === true) {
                return true
            } else {
                return false
            }
        }
    }   else {
        return true
    }
}

// 降序比较函数
const compare = (p) => {
    return (m, n) => {
        const a = m[p]
        const b = n[p]
        return b - a
    }
}

// 对菜单进行排序
const sortRouters = (accessedRouters) => {
    for (let i = 0; i < accessedRouters.length; i++) {
        const router = accessedRouters[i]
        if (router.children && router.children.length > 0) {
            router.children.sort(compare('sort'))
        }
    }
    accessedRouters.sort(compare('sort'))
}

/**
 * 异步生成菜单树， 方案二
 * @param dataList
 */
// const list2tree = (items, parentId = 0, arr = [], pathPrefix = '') => {
//     return items.filter(item => item.parentId == parentId).map((item: any) => {
//         const { icon, id, name, parentId, sort, keepAlive, meta, url } = item
//         let path = url.startsWith('/') ? url : '/' + url
//         path = url.startsWith(pathPrefix) ? path : pathPrefix + path
//         path = [...new Set(path.split('/'))].join('/')

//         // 路由对应的组件
//         const component = (constantRouterComponents[path]) || Empty || (() => import('@/views/shared/error/404.vue'))

//         return {
//             path: path,
//             // 路由名称，建议唯一
//             name: path || '',
//             children: list2tree(items, item.id, [], path),
//             // 该路由对应页面的 组件 (动态加载)
//             component: component,
//             props: true,
//             // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
//             meta: {
//                 title: meta?.title || name,
//                 icon: icon || 'icon-zhuomian',
//                 // hiddenHeaderContent: hiddenHeaderContent,
//                 // permission: item.actions || []
//                 keepAlive: keepAlive == 1,
//                 reload: false,
//                 componentName: component.name,
//                 // TODO 简单模拟CRUD权限：创建（Create）、更新（Update）、读取（Retrieve）和删除（Delete）操作，可以自行修改查看页面效果
//                 permission: parentId == -1
//                     ? []
//                     : ['create', 'update', 'retrieve', 'delete'].map(n => `${url.split('/').filter(m => m.trim() != '').join('.')}.${n}`)
//             }
//         }
//     }).sort((a, b) => a.sort - b.sort)
// }

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (): Promise<RouteRecordRaw[]> => {
    return new Promise((resolve, reject) => {
        adminMenus().then(result => {
            const { menus } = result
            const accessedRouters = asyncRouterMap.filter(v => {
                if (hasPermission(menus, v)) {
                    if (v.children && v.children.length > 0) {
                        v.children = v.children.filter(child => {
                            if (hasPermission(menus, child)) {
                                return child
                            }
                            return false
                        })
                        return v
                    } else {
                        return v
                    }
                }
                return false
            })
            // 菜单排序
            sortRouters(accessedRouters)

            accessedRouters.forEach(v => {
                // 设置模块重定向到菜单
                if ((v.children as any).length > 0 && !v.redirect) {
                    v.redirect = { name: (v.children as any)[0].name }
                }
            })
            const layout = routes.find(item => item.name == 'Layout')!
            
            layout.children = [
                ...common,
                ...accessedRouters
            ]
            router.addRoute(layout)
            router.addRoute(notFound)
            resolve(layout.children)
        }) 
    })
}

// export const generatorDynamicRouter = (): Promise<RouteRecordRaw[]> => {
//     return new Promise((resolve, reject) => {
//         console.log('generatorDynamicRouter')
//         adminMenus().then(result => {
//             console.log('result', result)
//             const menuNav: any = []
//             const childrenNav = []
//             //      后端数据, 根级树数组,  根级 PID
//             // listToTree(data, childrenNav, 0)
//             // rootRouter.children = childrenNav
//             menuNav.push(childrenNav)
//             const routeList = list2tree(result.menus)
//             console.log(routeList, '根据后端返回的权限路由生成')
//             routeList.forEach(item => {
//                 // 设置模块重定向到菜单
//                 if (item.children?.length > 0 && !item.redirect) {
//                     item.redirect = { name: item.children[0].name }
//                 }
//             })
//             const layout = routes.find(item => item.name == 'Layout')!
//             layout.children = [
//                 ...common,
//                 ...routeList
//             ]
//             router.addRoute(layout)
//             router.addRoute(notFound)
//             console.log('router', router)
//             resolve(layout.children)
//         }).catch(err => {
//             reject(err)
//         })
//     })
// }
